{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Adding Google Search Capability to AG2\n",
    "\n",
    "The Google Search integration in AG2 allows users to perform real-time web searches within the AG2 framework. This is especially useful for retrieving up-to-date information that may not be available in static datasets. \n",
    "\n",
    "## Installation\n",
    "\n",
    "To get started with the `Google Search` integration in AG2, follow these steps:\n",
    "\n",
    "Install AG2 with the `google-search` extra.\n",
    "Since our examples also use `openai` and `gemini`, install them as well:\n",
    "   \n",
    "```bash\n",
    "pip install -U ag2[openai,gemini,google-search]\n",
    "```\n",
    "> **Note:** If you have been using `autogen` or `ag2`, all you need to do is upgrade it using:  \n",
    "> ```bash\n",
    "> pip install -U autogen[openai,gemini,google-search]\n",
    "> ```\n",
    "> or  \n",
    "> ```bash\n",
    "> pip install -U ag2[openai,gemini,google-search]\n",
    "> ```\n",
    "> as `autogen`, and `ag2` are aliases for the same PyPI package.\n",
    "\n",
    "You're all set! Now you can start using Google Search with AG2.\n",
    "\n",
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "import autogen\n",
    "from autogen import AssistantAgent\n",
    "from autogen.tools.experimental import GoogleSearchTool"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using GoogleSearchTool with Gemini GenAI\n",
    "\n",
    "The `GoogleSearchTool` enables search functionalities in AG2 and can be configured to use Gemini GenAI for an enhanced search experience. This section covers agent configuration and tool initialization.\n",
    "\n",
    "### Agent Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "config_list = autogen.config_list_from_json(\n",
    "    env_or_file=\"OAI_CONFIG_LIST\",\n",
    "    filter_dict={\n",
    "        \"model\": [\"gemini-2.0-flash\"],\n",
    "    },\n",
    ")\n",
    "\n",
    "assistant = AssistantAgent(\n",
    "    name=\"assistant\",\n",
    "    llm_config={\"config_list\": config_list},\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### GoogleSearchTool Initialization\n",
    "\n",
    "For Gemini GenAI, you can use the GenAI prebuilt Google Search tool by setting `use_internal_llm_tool_if_available` to `True`.\n",
    "\n",
    "> **Note:** You cannot combine other tools with the prebuilt Google Search tool. If you need multiple tools, refer to the AG2 implementation section.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gs_tool = GoogleSearchTool(\n",
    "    use_internal_llm_tool_if_available=True,\n",
    ")\n",
    "# Once initialized, register the tool with the assistant\n",
    "gs_tool.register_for_llm(assistant)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Start the Conversation\n",
    "\n",
    "With the setup complete, you can now use the assistant to fetch live web search results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_response = assistant.run(\n",
    "    message=\"What happened with stock prices after deepseek was launched, please search the web.\",\n",
    "    tools=assistant.tools,\n",
    "    max_turns=2,\n",
    "    user_input=False,\n",
    ")\n",
    "run_response.process()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## GoogleSearchTool with AG2 Google Search implementation\n",
    "\n",
    "For all other LLM providers or if you need to combine Google Search with other tools, follow this section to configure AG2’s implementation.\n",
    "\n",
    "### Setup Google Search Engine and API Key\n",
    "1. Create a Google Custom Search Engine (CSE):\n",
    "   - [Go to Google Programmable Search Engine](https://programmablesearchengine.google.com/about/)\n",
    "   - Click `Get Started` and create a search engine.\n",
    "   - Under `Sites to Search`, select `Search the entire web` if you want global search.\n",
    "   - Copy the **Search Engine ID** from the CSE dashboard  (`cx` parameter from the url)\n",
    "2. Get a Google API Key:\n",
    "   - Go to [Google Cloud Console](https://console.cloud.google.com/)\n",
    "   - Create a new project.\n",
    "   - Navigate to **APIs & Services > Library**, search for **Custom Search API** and enable it.\n",
    "   - Go to **APIs & Services > Credentials**, click on **Create Credentials > API key** and copy it.\n",
    "3. Export engine ID and api key\n",
    "    ```bash\n",
    "    export GOOGLE_SEARCH_ENGINE_ID=\"your_engine_id\"\n",
    "    export GOOGLE_SEARCH_API_KEY=\"your_api_key\"\n",
    "    ```\n",
    "\n",
    "### Agent Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "config_list = autogen.config_list_from_json(\n",
    "    env_or_file=\"OAI_CONFIG_LIST\",\n",
    "    filter_dict={\n",
    "        \"model\": [\"gpt-5-nano\"],\n",
    "    },\n",
    ")\n",
    "\n",
    "assistant = AssistantAgent(\n",
    "    name=\"assistant\",\n",
    "    llm_config={\"config_list\": config_list},\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### GoogleSearchTool Initialization\n",
    "\n",
    "Create `GoogleSearchTool` with your `search_api_key` and `search_engine_id`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "search_api_key = os.getenv(\"GOOGLE_SEARCH_API_KEY\")\n",
    "search_engine_id = os.getenv(\"GOOGLE_SEARCH_ENGINE_ID\")\n",
    "\n",
    "assert search_api_key is not None, \"Please set GOOGLE_SEARCH_API_KEY environment variable\"\n",
    "assert search_engine_id is not None, \"Please set GOOGLE_SEARCH_ENGINE_ID environment variable\"\n",
    "\n",
    "gs_tool = GoogleSearchTool(\n",
    "    search_api_key=search_api_key,\n",
    "    search_engine_id=search_engine_id,\n",
    ")\n",
    "# Once initialized, register the tool with the assistant:\n",
    "gs_tool.register_for_llm(assistant)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Start the Conversation\n",
    "\n",
    "With the setup complete, you can now use the assistant to fetch live web search results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_response = assistant.run(\n",
    "    message=\"What happened with stock prices after deepseek was launched, please search the web.\",\n",
    "    tools=assistant.tools,\n",
    "    max_turns=2,\n",
    "    user_input=False,\n",
    ")\n",
    "run_response.process()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "front_matter": {
   "description": "Google Search",
   "tags": [
    "agents",
    "tools",
    "search",
    "web",
    "google",
    "real-time search"
   ]
  },
  "kernelspec": {
   "display_name": ".venv-google-search",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
